package ac.github.os.api.central

import ac.github.os.internal.core.skill.Coolable
import ac.github.os.internal.core.skill.SkillScheme
import ac.github.os.internal.core.trigger.IdTrigger
import org.bukkit.entity.Entity
import org.bukkit.entity.Player
import taboolib.common.platform.Awake
import taboolib.common.platform.function.submit
import java.util.*

object SkillCentral {

    var map = mutableMapOf<Any, MutableMap<Coolable, Double>>()

    @Awake
    fun task() {
        submit(async = true, period = 20) {
            map.forEach {
                val mutableMap = it.value
                val filter = mutableMap.filter { it.value - System.currentTimeMillis() <= 0 }
                filter.keys.forEach { coolable ->
                    coolable.onEnd()
                    mutableMap.remove(coolable)
                }
            }
        }
    }

    fun surplus(trigger: IdTrigger, coolable: Coolable): Double {
        val cache = getCache(trigger)
        val entryLongMapOrDefault = cache[coolable] ?: 0.0
        return entryLongMapOrDefault - System.currentTimeMillis()
    }


    fun end(trigger: IdTrigger, coolable: Coolable): Boolean {
        return surplus(trigger, coolable) <= 0
    }

    fun getCooldown(trigger: IdTrigger): MutableMap<Coolable, Double> {
        return getCache(trigger).filter { !end(trigger, it.key) }.toMutableMap()
    }

    fun included(trigger: IdTrigger, coolable: Coolable, endStamp: Double) {
        getCache(trigger)[coolable] = endStamp
    }

    fun getCache(trigger: IdTrigger): MutableMap<Coolable, Double> {
        return map.computeIfAbsent(trigger.id()) { mutableMapOf() }
    }

}